package com.swak.reactivex.context;

import java.util.Stack;

/**
 * 绑定线程中的事务
 * 
 * @author DELL
 */
public class StackThreadContext<T> {

	private final ThreadLocal<Stack<T>> resources = new ThreadLocal<>();

	public T get() {
		return _get();
	}

	public void bind(T context) {
		_put(context);
	}

	public void remove() {
		_remove();
	}

	T _get() {
		Stack<T> stack = resources.get();
		if (stack != null && !stack.isEmpty()) {
			return stack.peek();
		} else if (stack != null) {
			stack.clear();
			resources.remove();
		}
		return null;
	}

	/**
	 * 添加属性
	 * 
	 * @param key
	 * @param value
	 */
	void _put(T context) {
		Stack<T> stacks = resources.get();
		if (stacks == null) {
			stacks = new Stack<T>();
			resources.set(stacks);
		}
		stacks.push(context);
	}

	/**
	 * 添加属性
	 * 
	 * @param key
	 * @param value
	 */
	void _remove() {
		Stack<T> stacks = resources.get();
		if (stacks != null) {
			stacks.pop();
			if (stacks.isEmpty()) {
				resources.remove();
			}
		}
	}
}
